<?php

class SendMultiMessForm extends Form {

    private $total_record = 0;

    function SendMultiMessForm() {
        Form::Form('SendMultiMessForm');
        CGlobal::$website_title = "Gửi tin nhắn cho tất cả thành viên";
        $this->link_js('javascript/jquery/markitup/sets/bbcode/set.js');
        $this->link_js('javascript/jquery/markitup/jquery.markitup.js');
        $this->link_css('style/aznet/bbcode.css');
        $this->link_js('javascript/jquery/ui.datepicker.js');
        $this->link_css('style/aznet/ui.datepicker.css');
        $this->link_css('style/enbacStyle.css');
    }

    function on_submit() {
        $title = AZLib::getParam('subject');
        $content = AZLib::getParam('content');
        $id_cats = AZLib::getParam('id_cats');
        $send_all = AZLib::getParam('send_all');
        $usernames = Url::get('user_names');
        $start_date = Url::get('start_date');
        $end_date = Url::get('end_date');
        $start_date_a = Url::get('start_date_a');
        $end_date_a = Url::get('end_date_a');
        $is_active = Url::get('user_active');

        set_time_limit(0);

        if ($id_cats != 0) {//gửi cho thành viên bán theo chuyên mục
            $sql_user_sell = 'SELECT user_id, user_name FROM item ';

            AZLib::getCats();

            if (CGlobal::$allCategories[$id_cats]['parent_id'] > 0) {
                $condition = ' category_id = "' . $id_cats . '"';
            } else {
                $condition = ' level_1_catid = "' . $id_cats . '"';
            }

            $num_row = mysql_fetch_assoc(DB::query("SELECT count(*) as num_total FROM (SELECT count(*) FROM item WHERE status=1 AND $condition GROUP BY user_id) AS i"));

            if ($num_row) {
                $num_row = (int) $num_row['num_total'];
            } else {
                $num_row = 0;
            }

            if ($num_row) {
                $num_record = 100;
                $num_query = ceil($num_row / $num_record);

                $new_row_msg = array(
                    'msg_date' => TIME_NOW,
                    'msg_post' => htmlspecialchars_decode(addslashes($content)),
                    'msg_sent_to_count' => $num_row,
                    'msg_deleted_count' => 0,
                    'msg_author_id' => User::$current->data['id'],
                    'msg_author_name' => User::$current->data['user_name'],
                    'msg_ip_address' => AZLib::ip()
                );

                if ($title && $content && $num_row > 0) {
                    $msg_id = DB::insert('message_text', $new_row_msg);
                    for ($j = 0; $j < $num_query; $j++) {
                        $value_sql = '';
                        $update_sql = '';
                        $user = array();

                        $sql = 'SELECT user_id, item.user_name FROM item WHERE status=1 AND ' . $condition . ' GROUP BY user_id LIMIT ' . ($j * $num_record) . "," . $num_record;
                        $re = DB::query($sql);

                        if ($re) {
                            while ($user = mysql_fetch_assoc($re)) {
                                $value_sql .= ( $value_sql ? "," : "") . "('" . $msg_id . "','" . TIME_NOW . "','" . $title . "','" . User::id() . "','" . User::user_name() . "','inbox','" . $user['user_id'] . "','" . $user['user_name'] . "')";
                                $update_sql .= ( $update_sql ? "," : "") . $user['user_id'];

                                $this->total_record++;
                            }

                            $insert_sql = "INSERT INTO `message_topics` (`mt_msg_id`,`mt_date`,`mt_title`, `mt_from_id`, `mt_to_name`, `mt_vid_folder`, `mt_owner_id`, `mt_owner_name`) VALUES " . $value_sql;

                            DB::query($insert_sql);
                            DB::query('UPDATE user SET total_pm = total_pm + 1 WHERE id IN(' . $update_sql . ')');
                        }
                    }
                }
            }
        } elseif ($usernames != '' || $start_date != '' || $end_date != '' || $is_active) {

            $where = 'WHERE is_active = 0 AND block_time <= ' . TIME_NOW;

            if ($usernames != '') {//theo danh sách tài khoản thành viên
                $usernames = str_replace(' ', '', $usernames);
                $usernames = str_replace('"', '', $usernames);
                $usernames = str_replace("'", '', $usernames);
                $usernames = str_replace(',', "','", $usernames);

                $where .= " AND user_name IN ('" . $usernames . "') ";
            } else if ($is_active) { // gửi cho thành viên chính thức
                $where .= " AND level>0";
                if ($start_date_a != '' && strtotime($start_date_a)) {
                    $where .= " AND create_time>=" . strtotime($start_date_a);
                }

                if ($end_date_a != '' && strtotime($end_date_a)) {
                    $where .= " AND create_time<" . strtotime($end_date_a);
                }
            } else {//theo ngay thang nam
                if ($start_date != '' && strtotime($start_date)) {
                    $where .= " AND create_time>=" . strtotime($start_date);
                }

                if ($end_date != '' && strtotime($end_date)) {
                    $where .= " AND create_time<" . strtotime($end_date);
                }
            }

            $count_total_user = 'SELECT COUNT(*) AS total FROM user ' . $where;
           // echo $count_total_user;
           // exit;

            $num_row = DB::fetch($count_total_user);
            $num_record = 1000;
            $num_query = ceil($num_row['total'] / $num_record);

            $new_row_msg = array(
                'msg_date' => TIME_NOW,
                'msg_post' => htmlspecialchars_decode(addslashes($content)),
                'msg_sent_to_count' => $num_row['total'],
                'msg_deleted_count' => 0,
                'msg_author_id' => User::$current->data['id'],
                'msg_author_name' => User::$current->data['user_name'],
                'msg_ip_address' => AZLib::ip()
            );

            if ($title && $content && $num_row['total'] > 0) {
                $msg_id = DB::insert('message_text', $new_row_msg);

                for ($j = 0; $j < $num_query; $j++) {
                    $value_sql = '';
                    $update_sql = '';
                    $user = array();
                    $sql = "SELECT id, user_name FROM user " . $where . " ORDER BY id DESC LIMIT " . ($j * $num_record) . "," . $num_record;
                    $re = DB::query($sql);

                    if ($re) {
                        while ($user = mysql_fetch_assoc($re)) {
                            $value_sql.= ( $value_sql ? "," : "") . "('" . $msg_id . "','" . TIME_NOW . "','" . $title . "','" . User::id() . "','" . User::user_name() . "','inbox','" . $user['id'] . "','" . $user['user_name'] . "')";
                            $update_sql .= ( $update_sql ? "," : "") . $user['id'];

                            User::getUser($user['id'], 0, 1);
                            $this->total_record++;
                        }

                        $insert_sql = "INSERT INTO `message_topics` (`mt_msg_id`,`mt_date`,`mt_title`, `mt_from_id`, `mt_to_name`, `mt_vid_folder`, `mt_owner_id`, `mt_owner_name`) VALUES " . $value_sql;

                        DB::query($insert_sql);
                        DB::query('UPDATE user SET total_pm = total_pm + 1 WHERE id IN(' . $update_sql . ')');
                    }
                }
            }
        }

        Url::redirect('send_multi', array('action' => 'send', 'total' => $this->total_record));
    }

    function draw() {

        require_once 'modules/ManageContent/forms/ManageContent.php';
        $this->beginForm();
        global $display;
        $display->add('action', AZLib::getParam('action'));


        $total = ($this->total_record) ? $this->total_record : Url::get('total');

        if ($total) {
            $this->setFormSucces("", "Đã gửi tin nhắn cho $total thành viên!");
        }

        $display->add('msg', $this->showFormSuccesMessages(1));

        $display->add('send_all', AZLib::getParam('send_all'));
        $display->add('user_sell', AZLib::getParam('user_sell'));
        $display->add('subject', AZLib::getParam('subject'));
        $display->add('content', AZLib::getParam('content'));
        $display->add('item_cat', AZLib::getOption(ManageContentForm::getOtionCats(), Url::get('id_cats')));
        $display->output('send_multi_mess');
        $this->endForm();
    }

}

?>